package com.cartoon.fragment;


import android.content.Intent;
import android.view.View;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cartoon.R;
import com.cartoon.activity.CartoonDetailsActivity;
import com.cartoon.adapter.CartoonLrytAdapter;
import com.cartoon.adapter.CartoonTypeAdapter;

import com.cartoon.adapter.CarttonKKAdapter;
import com.cartoon.databinding.CartoonFrgmentBinding;
import com.cartoon.model.CartoonTypeModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.smtt.export.external.interfaces.IX5WebViewBase;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.ArrayList;
import java.util.HashMap;

import base.QFragment;
import base.QLoading;
import constant.AppConstants;
import http.Api;
import model.AnimeLRYSearchModel;
import model.AnimeYHSearchModel;
import model.CartoonLRYSearchModel;
import model.CarttonKKDirectoryModel;
import model.CarttonKKTypeModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class CartoonFragment extends QFragment<CartoonFrgmentBinding> {
    private HashMap map = new HashMap<Integer, String>();
    private ArrayList<CartoonTypeModel> typeList = new ArrayList<>();
    private CartoonTypeAdapter cartoonTypeAdapter;
    private int kkTypeId;
    private CartoonLrytAdapter cartoonLrytAdapter;
    private CarttonKKAdapter carttonKKAdapter;
    private int kkId;
    private QLoading dialog;
    int pageNo = 1;
    int PageNoSize = 20;
    private String typeName;
    private int count;
    private ArrayList<CartoonLRYSearchModel.DataBean> lryList = new ArrayList<>();
    private String lryId;

    @Override
    public int getLayoutRes() {
        return R.layout.cartoon_frgment;
    }

    @Override
    public void initView() {

        typeList.clear();
//        typeList.add(new CartoonTypeModel(67, "日漫"));
//        typeList.add(new CartoonTypeModel(89, "重生"));
//        typeList.add(new CartoonTypeModel(68, "异能"));
        typeList.add(new CartoonTypeModel(93, "冒险"));
        typeList.add(new CartoonTypeModel(20, "恋爱"));
        typeList.add(new CartoonTypeModel(80, "穿越"));
        typeList.add(new CartoonTypeModel(22, "奇幻"));


        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.rvType.setLayoutManager(layoutManager);
        cartoonTypeAdapter = new CartoonTypeAdapter(R.layout.cartton_type_item, typeList);
        binding.rvType.setAdapter(cartoonTypeAdapter);
        kkTypeId = cartoonTypeAdapter.getData().get(0).getId();
        typeName = cartoonTypeAdapter.getData().get(0).getName();


        GridLayoutManager lryLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        lryLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvLry.setLayoutManager(lryLayoutManager);
        cartoonLrytAdapter = new CartoonLrytAdapter(R.layout.cartoon_content_item, null);
        binding.rvLry.setAdapter(cartoonLrytAdapter);


        GridLayoutManager kkyoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        kkyoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvKk.setLayoutManager(kkyoutManager);
        carttonKKAdapter = new CarttonKKAdapter(R.layout.cartoon_content_item, null);
        binding.rvKk.setAdapter(carttonKKAdapter);
        // 设置刷新头部和尾部为经典样式
        binding.swipeLry.setRefreshHeader(new ClassicsHeader(getContext()));
        binding.swipeLry.setRefreshFooter(new ClassicsFooter(getContext()));


    }

    @Override
    public void initData() {
//
//        Intent intent = new Intent(getActivity(), AnimeActivity.class);
//        startActivity(intent);

        binding.webView.stopLoading();
        binding.webView.getSettings().setJavaScriptEnabled(true);//
        binding.webView.setWebViewClient(new WebViewClient());

        // 启用缩放
        binding.webView.getSettings().setSupportZoom(true);
//         设置默认缩放比例
        binding.webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        // 设置WebView加载页面时缩小图片
        binding.webView.getSettings().setUseWideViewPort(true);
        binding.webView.getSettings().setLoadWithOverviewMode(true);
        binding.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        binding.webView.setVerticalScrollBarEnabled(true);
        binding.webView.setHorizontalScrollBarEnabled(false);
//
//
//        // 启用WebView硬件加速
//        binding.webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }

    @Override
    public void initListener() {

        binding.ivblack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.d("我点击了返回");
//为true时表示下一项，为false时表示上一项
                binding.webView.goBack();

            }
        });

        binding.swipeLry.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新
                LogUtils.d("下拉刷新");

                if (pageNo * 20 < count) {
                    LogUtils.d("下拉刷新B");
                    pageNo = pageNo + 1;
                    getLRYTypeData();
                    LogUtils.d("我做了网络请求A");
                } else {
                    binding.swipeLry.finishLoadMoreWithNoMoreData();
                    LogUtils.d("下拉刷新CC");
                }
//                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //上拉
                LogUtils.d("上拉刷新");
//                pageNo = 1;
                networkMessage();
                refreshLayout.finishRefresh();
            }
        });
        cartoonTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CartoonTypeModel item = (CartoonTypeModel) adapter.getData().get(position);
                kkTypeId = item.getId();
                typeName = item.getName();
                pageNo = 1;
                lryList.clear();
                cartoonTypeAdapter.setIndex(position);
                cartoonTypeAdapter.notifyDataSetChanged();
                networkMessage();
            }
        });


        cartoonLrytAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CartoonLRYSearchModel.DataBean item = (CartoonLRYSearchModel.DataBean) adapter.getData().get(position);

                lryId = item.getComicId();

                Intent intent = new Intent(getContext(), CartoonDetailsActivity.class);
                intent.putExtra("lryId", lryId);
                intent.putExtra("type", 2);
                startActivity(intent);
            }
        });

        carttonKKAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CarttonKKTypeModel.DataBean.TopicsBean item = (CarttonKKTypeModel.DataBean.TopicsBean) adapter.getData().get(position);

                kkId = item.getId();

                Intent intent = new Intent(getContext(), CartoonDetailsActivity.class);
                intent.putExtra("kkid", kkId);
                intent.putExtra("type", 1);
                startActivity(intent);
            }
        });
    }

    @Override
    public void networkMessage() {
        lryList.clear();
        int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, 1);

        if (anInt == 1) {
            dialog = new QLoading();
            dialog.showNow(getChildFragmentManager(), "");
            ;
            //KK漫画接口没有页码 所以没做刷新
            getKKTypeData();
            binding.rvKk.setVisibility(View.VISIBLE);
            binding.rvLry.setVisibility(View.GONE);
            binding.swipeLry.setVisibility(View.GONE);
            binding.webView.setVisibility(View.GONE);
            binding.ivblack.setVisibility(View.GONE);
        } else if (anInt == 2) {


//            binding.rvKk.setVisibility(View.GONE);
//            binding.rvLry.setVisibility(View.VISIBLE);
//            binding.swipeLry.setVisibility(View.VISIBLE);
//            getLRYTypeData();


            binding.rvKk.setVisibility(View.GONE);
            binding.rvLry.setVisibility(View.GONE);
            binding.swipeLry.setVisibility(View.GONE);
            binding.webView.setVisibility(View.VISIBLE);
            binding.ivblack.setVisibility(View.VISIBLE);
            binding.webView.loadUrl("https://www.hisoman.com/search.html");


        }
    }

    private void getLRYTypeData() {

        Call<CartoonLRYSearchModel> call = Api.getInstance().service.getLRYCartoonType(typeName, pageNo, PageNoSize);
        call.enqueue(new Callback<CartoonLRYSearchModel>() {
            @Override
            public void onResponse(Call<CartoonLRYSearchModel> call, Response<CartoonLRYSearchModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());

                if (response.body() != null && response.body().getData() != null) {
                    dialog.dismiss();
                    cartoonLrytAdapter.replaceData(response.body().getData());
                    count = response.body().getCount();

                    if (pageNo == 1) {
                        binding.rvLry.scrollToPosition(0);
                        cartoonLrytAdapter.replaceData(response.body().getData());
                    } else {
                        if (response.body().getData().size() == 0) {
                            binding.swipeLry.finishLoadMoreWithNoMoreData();
                        } else {
                            binding.swipeLry.finishLoadMore();
                        }
                    }
                    for (int i = 0; i < response.body().getData().size(); i++) {
                        lryList.add(response.body().getData().get(i));
                    }

                    cartoonLrytAdapter.replaceData(lryList);


//                    kkId = response.body().getData().getTopics().get(0).getId();
//                    lrySearchAnimeAdapter.replaceData(response.body().getData());
                } else {
                    dialog.dismiss();
                    if (response != null && response.body() != null && response.body().getMsg() != null) {
                        ToastUtils.showLong(response.body().getMsg() + "状态码:" + response.code());
                    }

                }

            }

            @Override
            public void onFailure(Call<CartoonLRYSearchModel> call, Throwable t) {
                LogUtils.d("请切换模式试下  网络请求失败:" + t.getMessage());
                ToastUtils.showLong("请切换模式  网络请求失败:" + t.getMessage());
            }
        });
    }

    public void getKKTypeData() {
        Call<CarttonKKTypeModel> call = Api.getInstance().service.getKKCartoonType(kkTypeId + "");
        call.enqueue(new Callback<CarttonKKTypeModel>() {
            @Override
            public void onResponse(Call<CarttonKKTypeModel> call, Response<CarttonKKTypeModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());

                if (response.body() != null && response.body().getData() != null) {
                    dialog.dismiss();
                    carttonKKAdapter.replaceData(response.body().getData().getTopics());
                    kkId = response.body().getData().getTopics().get(0).getId();
//                    lrySearchAnimeAdapter.replaceData(response.body().getData());
                } else {
                    dialog.dismiss();
                    if (response.body() != null && response.body().getMessage() != null) {
                        ToastUtils.showLong(response.body().getMessage() + "状态码:" + response.code());
                    }
                }

            }

            @Override
            public void onFailure(Call<CarttonKKTypeModel> call, Throwable t) {
                LogUtils.d("请切换模式试下  网络请求失败:" + t.getMessage());
                ToastUtils.showLong("请切换模式  网络请求失败:" + t.getMessage());
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        pageNo = 1;
    }

}
